<?php

namespace app\admin\controller\shopro\wechat;

use app\admin\model\shopro\Config;
use app\admin\model\shopro\user\User;
use app\common\controller\Backend;
use EasyWeChat\Factory;
use think\Db;

/**
 * 微信管理
 *
 * @icon fa fa-circle-o
 */
class msg extends Backend
{

    /**
     * Wechat模型对象
     * @var \app\admin\model\shopro\wechat\Msg
     */
    protected $model = null;
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\wechat\Msg;
        $this->configmodel = new Config();
    }

    /**
     * 查看
     */
    public function index()
    {
       //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            $this->success('推送消息', null, $result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加模板信息
     */
    public function add()
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $params = $this->request->post();
                $paramsData = json_decode($params['data']);
                $data['name'] = $paramsData->name;
                $data['content'] = $paramsData->content;
                $data['template_id'] = $paramsData->template_id;
                $data['params'] = $paramsData->params;
                $data['user_ids'] = empty($paramsData->user_ids)  ? implode(',',$paramsData->user_ids) : '';
                $res = $this->model->strict(false)->insert($data);
                Db::commit();
            } catch (\Exception $ex) {
                Db::rollback();
            }
            if(isset($res) && $res){
                return $this->success('添加成功');
            }else{
                return $this->error('添加失败');
            }
        }else{
                return $this->view->fetch();
        }
    }
    /**
     * 添加模板信息
     */
    public function edit($ids = null)
    {
        if(!$ids) {
            $ids = $this->request->get('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {

            Db::startTrans();
            try {
                $params = $this->request->post();
                $paramsData = json_decode($params['data']);
                $data['name'] = $paramsData->name;
                $data['content'] = $paramsData->content;
                $data['template_id'] = $paramsData->template_id;
                $data['params'] = $paramsData->params;
                $data['user_ids'] =empty($paramsData->user_ids)  ? implode(',',$paramsData->user_ids) : '';
                $res = Db::name('shopro_wechat_msg')->strict(false)->where(['id'=>$ids])->update($data);
                Db::commit();
            } catch (\Exception $ex) {
                Db::rollback();
            }
            if($res =='0'){
                return $this->success('修改成功');
            }else{
                return $this->error('修改失败');
            }
        }
        $this->assignconfig("row", $row);
        return $this->view->fetch();

    }
    /**
     * 微信公众号推送
     *
    */
    public function tuisong()
    {   
        $result =  input();
        $MsgData = $this->model->where(['id'=>$result['ids']])->find();
        $params = \json_decode($MsgData['params']) ;
        if(empty($MsgData['user_ids'])){
            $user = \think\Db::name('shopro_user_oauth')->field('openid')->select();
        }else{
            $user = \think\Db::name('shopro_user_oauth')->field('openid')->where("user_id in(".$MsgData['user_ids'].")")->select();
        }
        foreach($params as $key => $val){
            $param[$val->title]= $val->content;
        }
        foreach($user as $key => $vv){
            $openid = $vv['openid'];
            $this->smallWXmessage($openid,$MsgData['template_id'], $param);
        }
    }
    /**
     * 微信公众号推送
     * $openid string       用户id
     * $templateid string   模板id
     * $result array        模板参数数组
     */
    public function smallWXmessage($openid,$templateid,$result){
//        $configData = $this->configmodel->where(['name'=>'wxMiniProgram'])->find();
//        $configData = json_decode($configData['value']);
        $config = [
//            'app_id' => "$configData->app_id",
//            'secret' => "$configData->secret ",
            'app_id' => "wx41e3fa46bbc8f0ad",
            'secret' => "6b560fbd6101cb09455372e393a59686",
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        //不知道openid的情况下，在微信公众号平台的用户管理中为某个用户添加标签，查询该标签下的用户openid
//        usersOfTag(标签id,'')  详细参考easywecha官网
//        $user = $app->user_tag->usersOfTag(100, $nextOpenId = '');
//        var_dump($user);die;
        $res = $app->template_message->send(
            [
                'touser' =>"$openid",
                'template_id' => "$templateid",
                'data' => $result,
            ]
        );
        if($res['errcode'] == 0){
            $this->success("发送成功");
        }else{
            $this->error($res['errmsg']);
        }
	}
    //同步粉丝
    public function syncfans()
    {
        $wechatFans = new \app\admin\model\shopro\wechat\Fans;
        // 检测队列
        checkEnv('queue');

        try {
            //批量更新粉色关注状态为未关注
            $this->model->where('subscribe', 1)->update(['subscribe' => 0]);
            $wechat = new \addons\shopro\library\Wechat('wxOfficialAccount');
            $res = $wechat->asyncFans();
        } catch (\Exception $e) {  //如书写为（Exception $e）将无效
            if (strpos($e->getMessage(), 'ip')) {
                $this->error('请将当前IP地址加入公众号后台IP白名单');
            }
        }
        $this->success($res['msg']);
    }

    public function user()
    {
        $get = $this->request->get();
        $user = \think\Db::name('shopro_user_oauth')->where([
            'platform' => 'wxOfficialAccount',
            'openid' => $get['openid'],
        ])->find();
        if ($user) {
            $user_id = $user['user_id'];
            $this->success('找到用户', null, $user_id);
        } else {
            $this->error('暂未成为商城用户');
        }
    }

}
